<template>
  <div class="Container">

    <!--组织数据-->
    <div class="left-department">
      <div class="head-container">
        <el-input
          v-model="deptName"
          placeholder="请输入班级名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
      </div>
      <div class="head-container">
        <el-tree
          ref="tree"
          :data="deptOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          default-expand-all
          @node-click="handleNodeClick"
        />
      </div>
    </div>
    <!--用户数据-->
    <div class="right-users">

      <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px" class="right-users-form">
        <el-form-item label="用户账号" prop="username">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户账号"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="nickname">
          <el-input
            v-model="queryParams.nickname"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="small" style="width: 240px">
            <el-option v-for="dict in statusOptions" :key="dict.id" :label="dict.label" :value="dict.label" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="btnLine-system">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出 </el-button>
      </div>

      <el-table v-loading="loading" :data="userList" empty-text="暂无数据" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="用户账号" align="center" prop="username" :show-overflow-tooltip="true" />
        <el-table-column label="用户姓名" align="center" prop="nickname" :show-overflow-tooltip="true" />
        <el-table-column label="班级" align="center" prop="department.name" :show-overflow-tooltip="true" />
        <el-table-column label="手机号码" align="center" prop="phone" width="120" />
        <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)">重置</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户照片">
              <div class="picBox">
                <img v-if="form.photo" :src="photoShow">
              </div>

              <el-upload
                :action="uploadUrl"
                :headers="upHeaders"
                :show-file-list="false"
                :on-change="fileChange"
                :on-success="handleSuccess"
                :on-error="handleError"
              >
                <el-button>点击添加</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="班级" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :normalizer="normalizer"
                :disable-branch-nodes="true"
                :show-count="true"
                placeholder="请选择班级"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option v-for="dict in sexOptions" :key="dict.id" :label="dict.label" :value="dict.label" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option v-for="item in statusOptions" :key="item.id" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="form.roleIds" multiple placeholder="请选择">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位" prop="postIds">
              <el-select v-model="form.postIds" multiple placeholder="请选择">
                <el-option v-for="item in postOptions" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="introduction">
              <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">
          <el-checkbox v-model="upload.updateSupport" />
          是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus
} from '@/api/system/user'
import { getToken } from '@/utils/auth'
import { listDept } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'User',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 组织树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 组织名称
      deptName: undefined,
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: this.$API_BASE_URL + '/system/user/importData'

      },
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        username: undefined,
        nickname: undefined,
        status: undefined,
        deptId: undefined
      },
      // 表单校验
      rules: {
        username: [
          { required: true, message: '用户编号不能为空', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '班级不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        sex: [
          { required: true, message: '性别不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ]
      },
      excel_name: 'system_user',
      // 图片上传
      uploadUrl: this.$API_BASE_URL + '/task/analyse/uploadOnePhoto',
      upHeaders: { Authorization: 'Bearer ' + getToken() },
      file: null,
      fileList: [],
      photoShow: ''// 头像展示的地址
    }
  },
  watch: {
    // 根据名称筛选组织树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
    this.getDicts('user_status').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('sex').then(response => {
      this.sexOptions = response.data
    })
  },
  methods: {
    // 图片上传
    // 文件状态改变时的钩子
    fileChange(file) {
      this.file = file.raw
      console.log('---------添加了文件', this.file)
    },
    // 文件上传成功时的钩子
    handleSuccess(res) {
      this.$notify.success({
        title: '成功',
        message: `文件上传成功`
      })
      const url = res.data.file_url
      this.form.photo = url
      this.photoShow = this.$API_BASE_URL + '/upload/' + url

      console.log('---------上传成功，返回的地址', url)
      console.log('---------赋值地址', this.form.avatar)
    },
    // 文件上传失败时的钩子
    handleError() {
      this.$notify.error({
        title: '错误',
        message: `文件上传失败`
      })
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = response.data.items
        this.total = response.data.total
        this.loading = false
        console.log('------ this.userList', this.userList)
      }
      )
    },
    /** 查询组织下拉树结构 */
    getTreeselect() {
      listDept().then(response => {
        this.deptOptions = response.data
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.getList()
    },
    // 用户状态修改
    handleStatusChange(row) {
      const text = row.status === '0' ? '启用' : '停用'
      this.$confirm('确认要"' + text + '""' + row.userName + '"用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeUserStatus(row.userId, row.status)
      }).then(() => {
        this.msgSuccess(text + '成功')
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        photo: '',
        deptId: undefined,
        username: undefined,
        nickname: undefined,
        password: undefined,
        phone: undefined,
        sex: undefined,
        status: undefined,
        remark: undefined,
        postIds: [],
        roleIds: []
      }
      this.resetForm('form')
    },
    reset_query() {
      this.queryParams = {
        page: 1,
        limit: 10,
        username: undefined,
        nickname: undefined,
        status: undefined,
        deptId: undefined
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset_query()
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getTreeselect()
      getUser().then(response => {
        this.postOptions = response.data.postOptions
        this.roleOptions = response.data.roleOptions
        this.open = true
        this.title = '添加用户'
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      const userId = row.id || this.ids
      getUser(userId).then(response => {
        this.form = response.data.user
        this.postOptions = response.data.postOptions
        this.roleOptions = response.data.roleOptions
        this.form.postIds = response.data.user.postIds
        this.form.roleIds = response.data.user.roleIds
        this.photoShow = this.$API_BASE_URL + '/upload/' + this.form.photo
        this.open = true
        this.title = '修改用户'
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.username + '-' + row.nickname + '"的新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        const data = {
          'user_id': row.id,
          'password': value
        }
        resetUserPwd(data).then(response => {
          if (response.code === 20000) {
            this.msgSuccess('修改成功，新密码是：' + value)
          } else {
            this.msgSuccess(response.msg)
          }
        })
      }).catch(() => {
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) { // 修改
            updateUser(this.form).then(response => {
              if (response.code === 20000) {
                this.msgSuccess(response.message)
                this.open = false
                this.getList()
              }
            })
          } else {
            addUser(this.form).then(response => { // 新增
              if (response.code === 20000) {
                this.msgSuccess(response.message)
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(function() {
        return delUser(userIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有用户数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(response => {
        this.download('system_user', queryParams)
      }).catch(function() {
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system_user')
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
      console.log('处理')
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.detail || response.message, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
      console.log(file)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>

<style scoped>
.Container{
  display: flex;
  height: 100%;
}
.left-department{
  width:256px;
  flex-shrink: 0;
  padding: 10px;
  border-right: 1px solid #ddd;
  background: #fff
}
.right-users{
  flex: 1;
}
.btnLine-system{
  background: #fff;
  padding: 10px;
}
.right-users-form{
  background: #fff;
  padding:10px 10px 0;
}
.el-form--inline .el-form-item{
  margin-bottom: 10px;
}
.picBox{
  width: 100px;
  height: auto;
}
.picBox img{
  width: 100%;
}
</style>
